package com.siemens.industrial.web.mvc.service;

import com.siemens.industrial.utils.ConfigurationUtil;
import com.siemens.industrial.utils.GlobalResponseCode;
import com.siemens.industrial.utils.SiemensException;
import org.springframework.stereotype.Service;

import java.io.*;

/**
 * Created by qupen on 2016/12/30.
 */
@Service
public class ExcelService {

    public static byte[] getExcelBytes(String name) throws SiemensException {
        assert name != null&&!name.isEmpty();

        String fileName = String.format("%s%s", ConfigurationUtil.INSTANCE.getExcelPath(), name.toLowerCase());

        File file = new File(fileName);

        if (!file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                throw new SiemensException(GlobalResponseCode.ERROR_CREATE_DIR_FAILED);
            }
        }

        try {
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            return buffer;
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }

    public static byte[] getDeviceXmlBytes(String name) throws SiemensException {
        assert name != null&&!name.isEmpty();

        String fileName = String.format("%s%s", ConfigurationUtil.INSTANCE.getDeviceXmlPath(), name.toLowerCase());

        File file = new File(fileName);

        if (!file.getParentFile().exists()) {
            if (!file.getParentFile().mkdirs()) {
                throw new SiemensException(GlobalResponseCode.ERROR_CREATE_DIR_FAILED);
            }
        }

        try {
            InputStream fis = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            return buffer;
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }
}
